#!/usr/bin/python
import web
import mpdclient2

class mpd:
    def __init__(self):
        self.client = mpdclient2.connect()
        
    def cliente(self):
        return self.client
    
    def cerrar(self):
        return self.client.close()

class listpls:
    def GET(self):
        cl = create_list()
        listapls=cl.get_playlist()

class create_list:
    def dir_list(self,dir=''):
        m = mpd()
        listado = m.cliente().lsinfo(dir)
        llave = listado[0]['type']
      #  print "listado: %s " % listado[0][llave]#.replace(listado[0][llave].split('/')[:-1],''
        #last = listado[0][llave].split('/')[-1]
        goto = listado[0][llave].replace( listado[0][llave].split('/')[-1],'')
        gotoup = goto.replace( goto.split('/')[-1],'')
        thisdir = ''
        if len(gotoup)>2:
            print "full: %s " % gotoup
            print "restale: %s" % gotoup.split('/')[-2]
            print "volver: %s" % gotoup.replace( gotoup.split('/')[-2],'' ) 
            thisdir = gotoup.replace( gotoup.split('/')[-2],'' ) 
        web.render('listadodb.html')
        
    def get_playlist(self):
        m = mpd()
        listado=[]
        for s in m.cliente().playlistinfo():
            if s.has_key('file'): 
                sart,stit,songid=s['file'].split('/')[-1],'',1
                if s.has_key('artist'): sart=s['artist'].lower()
                if s.has_key('title'): stit= s['title'].lower()
                if s.has_key('id'): songid=  s['id']
                listado.append( [sart,stit,s['file'],songid] )
        web.render('listadopls.html')
        #m.cerrar()

class getdir:
    def GET(self,directories):
        cl = create_list()
        cl.dir_list(directories)

class index:        
    def GET(self):
        web.render('head.html')
        cl = create_list()
        cl.get_playlist()
        cl.dir_list()
        web.render('foot.html')

class current:
    def GET(self):
                 m = mpd()
                 currsong='cancion no disp'
                 cs = m.cliente().currentsong()
                 print cs
                 if cs.has_key('file'):
                     if cs.has_key('artist') and cs.has_key('title'):
                         currsong = '%s - %s ' % (cs['artist'],cs['title'])
                     else:
                         currsong = '%s' % cs['file'].split('/')[-1]
                 print currsong
        ##        m.cerrar()
        #print "no funciona temporalmente"

class search:
    def GET(self,tipo):
        m = mpd()
        busqueda = tipo.split('|')
        print m.cliente().search(busqueda[0],busqueda[1])
        m.cerrar()

class addtopls:
    def GET(self,archivo):
        m = mpd()
        m.cliente().add( archivo.replace('%20','') )
        m.cerrar()

class rmtopls:
    def GET(self,id):
        m = mpd()
        m.cliente().deleteid( int(id) )
        
class do:
    def GET(self,action):
        m = mpd()
        i = web.input(times=1)
        for c in range(int(i.times)):
            action = action.lower()
            if action == 'stop':
                m.cliente().stop()    
            elif action == 'pauseplay':
                status = m.cliente().status()
                if status['state'].lower() == 'play':
                    m.cliente().pause(1)
                elif status['state'] == 'pause':
                    m.cliente().pause(0)
                elif (status['state'] == 'stop') or not status:
                    m.cliente().play()
            elif action == 'prev':
                m.cliente().previous()
            elif action == 'next':
                m.cliente().next()
            elif action == 'rand':
                m.cliente().random()
        m.cerrar()

class listen:
    def GET(self,song):
        m = mpd()
        m.cliente().playid( int(song) )
        m.cerrar()

class img:
    def GET(self,image):
        web.header("Content-Type","image/png")
        print open('images/'+image).read()

class css:
    def GET(self,name):
        web.header("Content-Type","text/cssjavscript; charset=utf-8")
        print open('css/'+name).read()       

class js:
    def GET(self,name):
        web.header("Content-Type","text/javscript; charset=utf-8")
        print open('js/'+name).read()

urls = ( '/', 'index',
         '/do/(.*)','do', #[pauseplay|stop|prev|next|random]
         '/listen/(.*)','listen',
         '/extras/images/(.*)','img',
         '/extras/js/(.*)','js',
         '/extras/css/(.*)','css',
         '/current','current',
         '/search/(.*)','search',
         '/addtoplaylist/(.*)','addtopls',
         '/removetoplaylist/(.*)','rmtopls',
         '/listpls','listpls',
         '/getdir/(.*)','getdir')

#gc = getConfig()
#__ROOTPATH__ = gc.getroot() #'/var/lib/mpd/music/'

web.webapi.internalerror = web.debugerror

if __name__ == "__main__": 
    web.run(urls, globals(),web.reloader)
